//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { Body, fetch } from '@tauri-apps/api/http';


// {
//     "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDYqUvDn6wCT60dv16sIQIi2NWeT2PYFoM6VVNemhfx5fZLW1C8YpRogjFWRQkkAcEMSWPaKjEzLUPVBHlBSuk/pumpLCLyBHdtsXFnZNw1JAaiGZxqEawSwE4xbCFWzQXKqe4bcqmJCV0SpQltYB38hv8/NhZLzILUQ98nn2Q6sjbKmqWpoiKuj0tiG+uqK1SzpcUMxA5wIOl4/oLPAIuYpI+9QI5kUrxdXcJJJjL+GlzH8FDbh8e4Mr6UlhqXTt+827uw/TkJUCM2hekCyjLdG3Nsra1OPic/VjbfAcuHVqdGPQLHD1FwPnCwCA1U11JmWI4znm+tqkj0x9wBkHn2w78kjTVnEwZFS0fkf55TmXqwkXz77iEzw08bCg6xXyortDk9f+wt3SqINMF8T0NhjBRPThMUm6obneBmzFH4aHwyDyf1kJOge4rAxCl8/K1eaLuTFB/rCmbi9CP7MbSm5uAAdQG3jbpVYBCgv3yJwiny60hK3lCOctVzYUGwP2E= surface@TABLET-C3ET6M4O",
//     "id": "207384",
//     "url": null,
//     "title": "surface@TABLET-C3ET6M4O",
//     "verified": null,
//     "created_at": "2024-02-19T13:10:55.000+00:00",
//     "read_only": false
// }

export interface AtomGitSshKey {
    key: string;
    id: string;
    title: string;
}

export async function list_ssh_key(accessToken: string): Promise<AtomGitSshKey[]> {
    const url = `https://api.atomgit.com/user/keys?per_page=100`;
    const res = await fetch<AtomGitSshKey[]>(url, {
        method: "GET",
        timeout: 10,
        headers: {
            "Authorization": `Bearer ${accessToken}`,
        },
    });
    if (res.ok && res.status == 200) {
        return res.data;
    } else {
        console.log(res);
        throw "error list user ssh key";
    }
}

export async function add_ssh_key(accessToken: string, title: string, key: string): Promise<void> {
    const url = `https://api.atomgit.com/user/keys`;
    const res = await fetch<void>(url, {
        method: "POST",
        timeout: 10,
        headers: {
            "Authorization": `Bearer ${accessToken}`,
        },
        body: Body.json({
            title,
            key,
        }),
    });
    if (res.ok && res.status == 200) {
        return;
    } else {
        console.log(res);
        throw "error add user ssh key";
    }
}

export async function remove_ssh_key(accessToken: string, keyId: string | number): Promise<void> {
    const url = `https://api.atomgit.com/user/keys/${keyId}`;
    const res = await fetch<void>(url, {
        method: "DELETE",
        timeout: 10,
        headers: {
            "Authorization": `Bearer ${accessToken}`,
        },
    });
    if (res.ok && res.status == 200) {
        return ;
    } else {
        console.log(res);
        throw "error remove user ssh key";
    }
}